package com.flynn.rock.filter;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.DES;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Getter;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Getter
public class SysUsernamePasswordFilter extends UsernamePasswordAuthenticationFilter {

    private static final DES des = SecureUtil.des("rockKey2022".getBytes(StandardCharsets.UTF_8));

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals(HttpMethod.POST.name())) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        JSONObject jsonParam;
        try {
            jsonParam = JSONUtil.parseObj(request.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String username = jsonParam.getStr(getUsernameParameter());
        username = (username != null) ? username.trim() : "";
        String password = jsonParam.getStr(getPasswordParameter());
        password = (password != null) ? password : "";
        password = des.decryptStr(password);
        UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username, password);
        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);
        return this.getAuthenticationManager().authenticate(authRequest);
    }
}
